package com.example.app.handler;

import net.sf.calibur.engine.Event;
import net.sf.calibur.engine.task.Task;
import net.sf.calibur.transport.CommandMessageEvent;
import net.sf.calibur.transport.SessionLostEvent;
import static net.sf.calibur.i18n.R.*;

import com.example.app.AppContext;
import com.example.app.CommandHandler;
import com.example.app.Player;
import com.example.app.PlayerFactory;
import com.example.app.messagebean.Broadcast;
import com.example.app.messagebean.Login;
import com.example.app.messagebean.LoginResponse;
import com.example.app.messagebean.LogoutResponse;


public class PlayerManagementCommandHandler extends CommandHandler {
	public PlayerManagementCommandHandler() {
		super("Player-Management");

		// 玩家登录指令（1000）
		addTask(new Task(1000) {
			@Override
			public void execute(Event event) throws Exception {
				CommandMessageEvent cme = (CommandMessageEvent) event;
				Login loginBean = (Login) cme.getInput();
				Player player = PlayerFactory.getInstance().playerLogin(
						loginBean.getPassport(), loginBean.getPassword());

				// 把Player实例绑定到session上
				cme.getSession().setAttribute(AppContext.ATTR_PLAYER, player);
				
				// 发送登录成功响应
				LoginResponse resp = (LoginResponse) cme.getOutput();
				resp.setPlayerId(player.getId());
				resp.setErrorMessage(_("你已成功登入游戏。"));
				cme.sendResponse();
				
				logger.debug("玩家" + player + "登入系统");
				
				// 发送一条push消息给给客户端
				Broadcast push = getMessageBean(Broadcast.class);
				push.setMsg(_("你已成功登入游戏。"));
				cme.getSession().pushCommand(1004, push);
			}
		});

		// 玩家logout指令（1002）
		addTask(new Task(1001) {
			@Override
			public void execute(Event event) throws Exception {
				logger.debug("玩家logout");

				CommandMessageEvent cme = (CommandMessageEvent) event;
				Player player = (Player) cme.getSession().removeAttribute(
						AppContext.ATTR_PLAYER);
				if (player == null) {
					throw new RuntimeException("Session上还没有登录用户实例。");
				}

				PlayerFactory.getInstance().playerLogout(player);
				LogoutResponse resp = (LogoutResponse) cme.getOutput();
				resp.setErrorCode(0);
				resp.setGrace("欢迎再来!");
				cme.sendResponse();
				
				cme.getSession().close();
			}
		});
		
		// Session连接中断（断网)
		addTask(new Task(SessionLostEvent.class) {
			@Override
			public void execute(Event event) throws Exception {
				logger.info("与客户端连接断开...");
				SessionLostEvent sle = (SessionLostEvent) event;
				Player player = getBindPlayer(sle.getSession());
				if (player != null) {
					System.err.println("Player " + player + " 连接中断。");
					sle.getSession().removeAttribute(AppContext.ATTR_PLAYER);
					PlayerFactory.getInstance().playerLogout(player);
				} else {
					System.err.println("Session lost >>>> not found Player, do nothing...");
				}
			}
		});
	}
}
